<script setup>
import { computed, ref, watch, onMounted } from 'vue';
import { EyeInvisibleOutlined, EyeTwoTone, VerticalRightOutlined,UploadOutlined } from '@ant-design/icons-vue';
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn';
import { useRoute } from 'vue-router'
import rectangleBlue from "@/assets/rectangleBlue.png";
import { message } from 'ant-design-vue'
import PasswordTips from "@/components/PasswordTips.vue";
import {getStuInfo, stuRegister, updateStuInfo} from "@/api/stu.js";
import {uploadImage, userLogin} from '@/api/user.js'
import { userUserStore } from "@/stores/index.js";
import router from "@/router/router.js";
import {useLocStore} from "@/stores/location.js";
import {uploadFile} from "@/api/file.js";
import {registerCompany, uploadCompanyLogo} from "@/api/company.js";

// 三张表单
const formRef1 = ref()
const formRef2 = ref()
const formRef3 = ref()
const isRegister = ref(false)
const route = useRoute()
const userStore = userUserStore()

const locStore = useLocStore()
const openCity = ref(false);

//是否下一步

// 表单数据和验证
const phone = ref(route.query.phone)
const role = ref(route.query.role)
const formModel = ref({
  psd: '',
  repsd: '',
  username: '',
  companyName: '',
  logo: [],
  website: '',
  city: '',
});
const resLogo = ref('')

onMounted(() => {
  //获取phone
  const getPhone = () => {
    if (!phone.value || role.value!=='company') {
      router.replace('/register')
      message.error('出现异常');
    }
  };
  getPhone()
})

const openDag = ref(false);

const handleOk = () => {
  console.log(formModel.value.city)
  openCity.value = false
}

const nextSubmit = async () => {
  await (currentStep.value===0 ? await formRef1.value: formRef2.value).validate().then(async () => {
    nextStep()
  }).catch((err)=>{
    message.error('请检查输入的内容')
  })
}

const customRequest = async (file) => {
  const formData = new FormData();
  formData.append('file', file.file);
  try {

    const res = await uploadImage(formData, {
      onUploadProgress: ({total,loaded}) => {
        file.onProgress = ({percent: Math.round((loaded/total)*100).toFixed(2)},file)
      }
    });
    if (res.data.code !== 200) {
      throw new Error(res.data.message || '上传失败');
    }
    file.onSuccess(res?.data.data, file);
    resLogo.value = res?.data.data
  } catch (error) {
    message.error(error.message || '上传出错');
    file.onError(error, file);
  }
};

const beforeUpload = (file) => {
  return new Promise((resolve, reject) => {
    const supportedImageTypes = [
      'image/jpeg',
      'image/jpg', // 添加对 jpg 格式的支持
      'image/png',
    ];
    const isSupportedType = supportedImageTypes.includes(file.type);
    const isLt5M = file.size / 1024 / 1024 < 5;

    if (!isSupportedType) {
      message.error('仅支持上传 JPEG、JPG、PNG格式的图片');
      reject(false);
    }

    if (!isLt5M) {
      message.error('上传图片大小不能超过5MB');
      reject(false);
    }

    resolve(true);
  });
}

// 步骤条
const currentStep = ref(0);
const nextStep = () => {
  if (currentStep.value < 2) {
    currentStep.value++;
  }
};
const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--;
  }
};

// 密码验证
const validatepsd = async (_rules, value) => {
  if (value === '') {
    return Promise.reject('请输入密码');
  } else {
    if (value !== formModel.value.psd) {
      return Promise.reject('两次输入密码不一致');
    } else {
      return Promise.resolve();
    }
  }
};
const validaterepsd = async (_rules, value) => {
  if (value === '') {
    return Promise.reject('请再次输入密码');
  } else {
    if (value !== formModel.value.psd) {
      return Promise.reject('两次输入密码不一致');
    } else {
      return Promise.resolve();
    }
  }
};

// 前往上一步
const goToPreStep = () => {
  prevStep()
}

//同步信息
const onSubmit = async () => {
  await formRef3.value.validate().then(async () => {
    const res = await registerCompany({
      username: formModel.value.username,
      password: formModel.value.psd,
      repassword: formModel.value.repsd,
      companyName: formModel.value.companyName,
      logo: resLogo.value,
      website: formModel.value.website,
      city: formModel.value.city,
      phoneNum: phone.value,
    })
    if (res.data.code === 200) {
      userStore.setToken(res.data.token)
      message.success('注册成功,请等待审核')
      router.replace('/login')
    } else {
      message.error(res.data.message)
    }
  })
}

// 表单验证规则
const rules = {
  psd: [
    {required: true, validator: validatepsd, trigger: 'change'},
    {
      pattern: /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*(),.?":{}|<>_]).{8,20}$/,
      message: '密码必须满足下面的五个条件',
      trigger: 'change'
    }
  ],
  repsd: [{required: true, validator: validaterepsd, trigger: 'change'}],
  username: [
    {required: true, message: '请输入用户名', trigger: 'change'},
  ],
  companyName: [
    {required: true, message: '请输入公司名称', trigger: 'change'},
    {
      pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]{2,20}$/,
      message: '公司名称不能包含特殊字符，长度为2-20个字符',
      trigger: 'change'
    }
  ],
  logo: [{required: true, message: '请上传公司logo', trigger: 'change'}],
  website:[
      {required: true, message: '请输入公司网址', trigger: 'change'},
      {
        pattern: /^(https?:\/\/)?([\w-]+\.)+[\w-]+(\/[\w-./?%&=]*)?$/,
        message: '请输入正确的网址',
        trigger: 'change'
      }
  ]
};

const progress = {
  strokeColor: {
    '0%': '#108ee9',
    '100%': '#87d068',
  },
  strokeWidth: 3,
  format: percent => `${parseFloat(percent.toFixed(2))}%`,
  class: 'test',
};

dayjs.locale('zh-cn');
</script>

<template>
  <div class="main-container">
    <!-- Header -->
    <a-layout-header class="header">
      <h2 style="position: relative; top: -5px; left: 10px; color: #64d5c8;">实习招聘信息爬虫系统设计与实现</h2>
    </a-layout-header>

    <a-flex justify="center" align="center" gap="large" horizontal class="flex-container">
      <div class="card-container">
        <a-card class="form-wrapper">
          <div class="title-style">
            <a-image height="30px" width="10px" :src="rectangleBlue" :preview="false"></a-image>
            <span>完善账户信息</span>
          </div>
          <!-- 设置密码 -->
          <a-form ref="formRef1" v-if="currentStep === 0" :model="formModel" :rules="rules">
            <a-form-item label="" name="username">
              <a-input v-model:value="formModel.username" has-feedback placeholder="请输入用户名" style="height: 45px"/>
            </a-form-item>
            <a-form-item label="" name="psd">
              <a-input-password v-model:value="formModel.psd" has-feedback placeholder="请输入密码"
                                style="height: 45px"/>
              <template #iconRender="v">
                <EyeTwoTone v-if="v"></EyeTwoTone>
                <EyeInvisibleOutlined v-else></EyeInvisibleOutlined>
              </template>
            </a-form-item>
            <a-form-item label="" name="repsd">
              <a-input-password v-model:value="formModel.repsd" has-feedback placeholder="请再次输入密码"
                                style="height: 45px"/>
              <template #iconRender="v">
                <EyeTwoTone v-if="v"></EyeTwoTone>
                <EyeInvisibleOutlined v-else></EyeInvisibleOutlined>
              </template>
            </a-form-item>
            <a-form-item>
              <!--              :disabled="isNextSubmit" -->
              <a-button type="primary" @click="nextSubmit" block :disabled="isRegister">下一步</a-button>
            </a-form-item>
            <PasswordTips v-model:password="formModel.psd"></PasswordTips>
          </a-form>

          <!-- 设置公司名和所在城市 -->
          <a-form ref="formRef2" v-if="currentStep === 1" :model="formModel" :rules="rules">
            <div class="card-header">
              <div class="pre-step" @click="goToPreStep">
                <VerticalRightOutlined style="color: rgb(10, 124, 142)"/>
                <span>上一步</span>
              </div>
<!--              <div class="skip" @click="onSkip">-->
<!--                <span>跳过</span>-->
<!--              </div>-->
            </div>
            <a-form-item label="" name="companyName">
              <a-input v-model:value="formModel.companyName" has-feedback placeholder="请输入公司名" style="height: 45px"/>
            </a-form-item>
            <a-form-item label="" name="city">
              <a-input-group compact>
                <a-input disabled style="width: 70%;height: 45px" v-model:value="formModel.city"></a-input>
                <a-button style="width: 30%;height: 45px" type="primary" @click="openCity=true">选择城市</a-button>
              </a-input-group>
              <a-modal v-model:open="openCity" title="选择公司所在城市" @ok="handleOk">
                <div v-for="group in locStore.siteGroup">
                  {{ group.firstChar }}：
                  <a-radio-group v-model:value="formModel.city" style="margin-bottom: 10px;">
                    <a-radio-button v-for="city in group.cityList" :value="city.name">{{ city.name }}</a-radio-button>
                  </a-radio-group>
                </div>
              </a-modal>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" block @click="nextSubmit">下一步</a-button>
            </a-form-item>
          </a-form>

          <!-- 设置网站和logo -->
          <a-form ref="formRef3" v-if="currentStep === 2" :model="formModel" :rules="rules">
            <div class="card-header">
              <div class="pre-step" @click="goToPreStep">
                <VerticalRightOutlined style="color: rgb(10, 124, 142)"/>
                <span>上一步</span>
              </div>
<!--              <div class="skip" @click="onSkip">-->
<!--                <span>跳过</span>-->
<!--              </div>-->
            </div>
            <a-form-item label="" name="logo">
              <a-upload
                  v-model:file-list="formModel.logo"
                  list-type="picture"
                  maxCount="1"
                  :custom-request="customRequest"
                  :before-upload="beforeUpload"
                  :progress="progress"
              >
                <a-button>
                  <upload-outlined></upload-outlined>
                  上传一个图片，支持PNG,JPG,JPEG图片
                </a-button>
              </a-upload>
            </a-form-item>
            <a-form-item label="" name="website">
              <a-input v-model:value="formModel.website"
                       has-feedback
                       placeholder="输入公司网站"
                       style="height: 45px"/>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" block @click="onSubmit">确认</a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </div>
      <!-- 步骤条 -->
      <div class="step-container">
        <a-steps :current="currentStep" class="step" direction="vertical">
          <a-step disabled title="设置密码"/>
          <a-step disabled title="设置公司名和所在城市"/>
          <a-step disabled title="设置公司网站和logo"/>
        </a-steps>
      </div>
    </a-flex>
  </div>
</template>

<style scoped>
a-input {
  height: 45px;
}

.form-wrapper {
  width: 400px;
  margin: 100px;
  height: 500px;
  box-shadow: 0 4px 8px rgba(10, 124, 142, 0.1),
  0 -4px 8px rgba(10, 124, 142, 0.1),
  -4px 0 8px rgba(10, 124, 142, 0.1),
  4px 0 8px rgba(10, 124, 142, 0.1);
  padding: 20px;
  border-radius: 8px;
}

.title-style {
  display: flex;
  margin-top: 70px;
  text-align: left;
  font-size: 22px;
  color: rgb(10, 124, 142);
  transform: translateY(-30px);
  align-items: center;

  > span {
    position: absolute;
    margin-left: 20px;
  }
}

.step {
  height: 500px;
  transform: translateY(100px);
}

.flex-container {
  max-height: calc(100vh - 150px);
  width: 100%;
  /*background: url("src/assets/detailContent.png") center / cover no-repeat;*/
}

.check-mark {
  color: green;
  margin-left: 5px;
}

.psd-request {
  margin-left: -20px;
  margin-top: 30px;
}

.psd-request li.valid {
  color: green;
}

.psd-request li {
  font-size: 10px;
  color: #999999;
  white-space: nowrap;
}

.card-header {
  display: flex;
  justify-content: space-between;
}

.pre-step {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  cursor: pointer;

  > span {
    color: rgb(10, 124, 142);
    font-size: 12px;
  }
}

.skip {
  cursor: pointer;
  display: flex;
  text-align: center;

  > span {
    color: rgb(10, 124, 142);
    font-size: 14px;
  }
}

.header {
  height: 50px;
  background: url("src/assets/headerBg.png") center / cover no-repeat;
  color: #fff;
  padding: 16px;
}

.main-container {
  height: 100vh;
  position: absolute;
  width: 100%;
}

.upload-list-inline :deep(.ant-upload-list-item) {
  float: left;
  margin-right: 8px;
}
.upload-list-inline [class*='-upload-list-rtl'] :deep(.ant-upload-list-item) {
  float: right;
}

:deep(.css-dev-only-do-not-override-17yhhjv.ant-btn.ant-btn-default) {
  width: 310px;
  height: 40px;
}
</style>
